from PIL import Image
import numpy as np

img = Image.open("../resource/test_2.jpg")  # 打开图像
img_array = np.array(img)
w = img.size[0]
h = img.size[1]

N = np.zeros((256,), dtype=float)  # 直方图且标准化
for i in range(w):
    for j in range(h):
        N[img_array[j][i]] += 1
for i in range(256):
    N[i] = N[i] / (w * h)

S = np.zeros((256,), dtype=float)  # 直方图均衡化
for i in range(256):
    for j in range(i):
        S[i] += N[j]
    S[i] = S[i] * 255

result_array = np.zeros((h, w), dtype=int)  # 计算结果图
for i in range(h):
    for j in range(w):
        result_array[i][j] = round(S[img_array[i][j]])

result = Image.fromarray(np.uint8(result_array)).convert("L")
result.show()
result.save("../output_1.png")